/**
 * @Description WXSWOrderController.java
 * @author xu_cc [18724000100@163.com]
 * @date 创建时间：2017年12月28日 下午4:25:11
 */
package com.solution.wx.order.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.constants.OrderConstants.ORDER_APPROVE_STATUS;
import com.solution.admin.order.constants.OrderConstants.ORDER_PAY_MODEL;
import com.solution.admin.order.constants.OrderConstants.ORDER_STATUS;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.core.util.WechatUtil;

/**
 * 商务端-订单控制层
 * 
 * @author xu_cc
 * @date 创建时间：2017年12月28日 下午4:25:14
 */
@RequestMapping("/wx/sworder")
@Controller
public class WxswOrderController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(WxswOrderController.class);

	@Autowired
	private OrderService orderService;

	@Autowired
	private KeyMapService keyMapService;

	/**
	 * 分页查询我的订单
	 * 
	 * @param order
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/list")
	public String listOrderPage(HttpServletRequest request, HttpServletResponse response) {
		// 隐藏的参数，用于微信端下拉查询更多（分页）订单信息
		Map<String, Object> hiddenParamMap = new HashMap<String, Object>();
		// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
		String requestType = request.getParameter("requestType");
		String pageNumStr = request.getParameter("pageNum");
		if (StringUtil.isEmpty(pageNumStr)) {
			pageNumStr = "1";
		}
		int pageNum = Integer.parseInt(pageNumStr);
		int numPerPage = 3;
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 审核状态（01，通过 / 02=驳回）
		String approveResult = request.getParameter("approveResult");

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderStatus", orderStatus);
		paramMap.put("approveResult", approveResult);
		try {
			// PageBean pageBean = orderService.listMyOrderPage(pageParam,
			// paramMap);
			PageBean pageBean = orderService.listOrderPage(pageParam, paramMap);
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if (orderList != null && orderList.size() > 0) {
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity) object;
					String productDetail = order.getProductDetail();
					if (StringUtil.isNotEmpty(productDetail)) {
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "[" + productDetail + "]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						order.setProductList(orderDetailList);
					}
				}
			}
			// 如果是异步，直接写response
			if ("sync".equals(requestType)) {
				try {
					response.getWriter().write(JSONObject.toJSON(pageBean).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("orderList", pageBean.getRecordList());
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("orderStatus", orderStatus);
			request.setAttribute("approveResult", approveResult);
			hiddenParamMap.put("orderStatus", orderStatus);
			hiddenParamMap.put("approveResult", approveResult);
			request.setAttribute("hiddenParamMap", hiddenParamMap);

		} catch (Exception e) {
			handleException("分页查询微信订单信息失败", logger, e);
		}
		return "/wx/sworder/order_list";
	}
	
	/**
	 * 分页查询我的订单
	 * 
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/detail")
	public String toOrderDetail(HttpServletRequest request) {
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray("[" + order.getProductDetail() + "]", OrderDetailEntity.class);
					if (productList != null && productList.size() > 0) {
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
							product.setProductItemMoney((product.getProductAdjustPrice() == null ? product.getProductPrice() : product
							        .getProductAdjustPrice()).multiply(new BigDecimal(product.getBuyNum())));
							if (StringUtil.isNotEmpty(product.getProductSpec())) {
								List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);
								product.setProductSpecList(productSpecList);
							}
						}
					}
					request.setAttribute("productList", productList);
				}
				request.setAttribute("order", order);
			}
		} catch (Exception e) {
			handleException("查询我订单详情页面", logger, e);
		}
		return "/wx/sworder/order_detail";
	}

	/**
	 * 跳转订单驳回页面
	 * 
	 * @param request
	 *            请求对象
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toApproveOrder")
	public String toCancelOrder(HttpServletRequest request) {
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			// 查询订单驳回原因
			List<KeyMapEntity> rejectReasonList = keyMapService.listKeyMap("orderRejectReason");
			request.setAttribute("rejectReasonList", rejectReasonList);
			request.setAttribute("orderCode", orderCode);
		} catch (Exception e) {
			handleException("跳转订单驳回页面失败", logger, e);
		}
		return "/wx/sworder/order_approve";
	}

	/**
	 * 订单审核
	 * 
	 * @param request
	 * @return Map<String,Object>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月29日 上午11:46:50
	 */
	@RequestMapping("/approveOrder")
	@ResponseBody
	public Map<String, Object> approveOrders(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 订单号
			String orderCode = request.getParameter("orderCode");
			// 审批结果
			String approveResult = request.getParameter("approveResult");
			// 审批意见
			String approveReason = request.getParameter("approveReason");
			// 订单号、审核意见
			if (StringUtil.isEmpty(orderCode) || StringUtil.isEmpty(approveResult)) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "审核失败，请刷新重试！");
				return resultMap;
			}
			// 驳回原因
			// 驳回原因
			if (ORDER_APPROVE_STATUS.NOT_PASS.getCode().equals(approveResult) && StringUtil.isEmpty(approveReason)) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "审核失败，驳回原因为空！");
				return resultMap;
			}
			// 获取订单信息,验证订单当前状态
			OrderEntity order = orderService.getOrderByCode(orderCode);
			if (null == order) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "审核失败，未获取订单！");
				return resultMap;
			} else {
				// 验证订单状态
				if (!ORDER_STATUS.WAIT_TO_APPROVE.getCode().equals(order.getOrderStatus())) {
					resultMap.put(PublicStatus.RESULT_CODE, "0");
					resultMap.put(PublicStatus.RESULT_MSG, "审核失败，订单状态已变更，请刷新后重试！");
					return resultMap;
				} else {
					Map<String, Object> param = new HashMap<String, Object>();
					// 可以进行审核了
					String confirmType = "1";// 默认货到付款
					if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
						// 如果是立即支付
						confirmType = "2";
					}
					if (OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)) {
						// 待发货
						param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_SEND.getCode());
					} else {
						// 审核驳回 ，订单进入前台进行调整，重新上传合同或添加支付凭证
						param.put("orderStatus", OrderConstants.ORDER_STATUS.APPROVE_REJECTED.getCode());
					}
					param.put("orderCode", orderCode);
					param.put("approveResult", approveResult);
					param.put("approveReason", approveReason);
					param.put("approverCode", getUserCode()); // 审核人
					param.put("approverName", getUserName()); // 审批人姓名
					param.put("modifier", getUserName()); // 修改人姓名
					param.put("confirmType", confirmType); // 确认合同/付款凭证
					int result = orderService.approveOrder(param);
					resultMap.put(PublicStatus.RESULT_CODE, result > 0 ? "1" : "0");
					resultMap.put(PublicStatus.RESULT_MSG, result > 0 ? "操作成功" : "操作失败");
					return resultMap;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put(PublicStatus.RESULT_CODE, "-1");
			resultMap.put(PublicStatus.RESULT_MSG, "审核出错，请重试！");
			return resultMap;
		}
	}

	/**
	 * 跳转上传合同页面
	 * 
	 * @param request
	 *            请求对象
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toUploadOrderContract")
	public String toUploadContract(HttpServletRequest request) {
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {

			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("realPayMoney", order.getRealPayMoney());
			// 查询微信调用接口信息
			String jsapi_ticket = WechatUtil.getJspiTicket();
			String url = request.getRequestURL().toString();
			String urlParam = request.getQueryString();
			if (StringUtil.isNotNull(urlParam)) {
				url = url + "?" + urlParam;
			}
			Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
			request.setAttribute("appId", WechatUtil.APPID);
			request.setAttribute("timestamp", sign.get("timestamp"));
			request.setAttribute("nonceStr", sign.get("nonceStr"));
			request.setAttribute("signature", sign.get("signature"));

			request.setAttribute("orderCode", orderCode);
		} catch (Exception e) {
			handleException("跳转上传合同页面", logger, e);
		}
		return "/wx/sworder/order_upload_contract";
	}

}
